package cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.consumer;

import cn.edu.zstu.qingzhu.qingzhushop.entity.Order;
import cn.edu.zstu.qingzhu.qingzhushop.entity.Seckill;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.OrderMapper;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.SeckillMapper;
import cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.publisher.SecKillDeadPublisher;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * FileName: SecKillDeadConsumer
 *
 * @Author: LvYibin
 * @Date: 2021/5/17 12:33
 * @Description:
 */
@Component
@RabbitListener(queues = "queue.seckill",containerFactory = "singleListenerContainer")
public class SecKillDeadConsumer {
    private static final Logger log= LoggerFactory.getLogger(SecKillDeadPublisher.class);
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    SeckillMapper seckillMapper;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 监听并消费队列中的消息-在这里采用单一容器工厂实例即可
     */
    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void consumeMsg(@Payload byte[] msg){
        try {

            //String message=new String(msg, StandardCharsets.UTF_8);
//            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
//            List<DeadInfo> list = objectMapper.readValue(new String(msg, StandardCharsets.UTF_8),
//                    new TypeReference<List<DeadInfo>>(){/**/});
            Integer id = new Integer(new String(msg, StandardCharsets.UTF_8));
            Seckill seckill = seckillMapper.selectById(id);
            seckill.setIsActive(1);
            redisTemplate.opsForValue().set(seckill.getOnlyseckill()+":status",1,10L, TimeUnit.MINUTES);
            seckillMapper.updateById(seckill);
//            DeadInfo list = objectMapper.readValue(new String(msg,StandardCharsets.UTF_8),DeadInfo.class);
            log.info("死信消息模型-消费者-消费消息-订单编号：{}",id);

        }catch (Exception e){
            log.error("死信消息模型-消费者-发生异常：",e.fillInStackTrace());
        }
    }
}
